<template>
    <div>
        <!-- 小播放器 -->
        <div class="player-box" v-cloak v-if="playerId">
            <div :class="['img','play',{'pause':isShow}]" @click="playerShow = true"><img :src="SongDetail.al.picUrl" alt=""></div>
            <div class="name-box">
                <div class="song-name" v-text="songName"></div>
                <div class="people-name">
                    <span v-for="(item,index) in SongDetail.ar" :key="index">{{item.name}}</span>
                </div>
            </div>
            <div class="icon-box" @click.stop="toggleplay">
                <span class="icon iconfont icon-zanting" v-show="isShow"></span>
                <span class="icon iconfont icon-ico_zanting_xuanzhong" v-show="!isShow"></span>
            </div>
            <div class="more-box">
                <span class="more iconfont icon-fenlei" @click="playMenuShow = true"></span>
            </div>
        </div>
        <!-- 大播放器 -->
        <transition name="player">
            <div class="big-player" v-if="playerShow">
                <!-- 向下icon -->
                <span class="iconfont icon-arrow-down-bold icon" @click="playerShow = false"></span>
                <!-- 头部 -->
                <div class="big-player-header">
                    <div class="song-name">{{SongDetail.name}}</div>
                    <div class="singer-name">
                        <span v-for="(item,index) in SongDetail.ar" :key="index">{{item.name}}</span>
                    </div>
                </div>
                <!-- 中间大图片 -->
                <div class="big-img-box">
                    <div v-show="togglelyric == true"  @click="togglelyric=false" :class="['img','play',{'pause':isShow}]">
                        <img :src="SongDetail.al.picUrl">
                    </div>
                    <div v-show="togglelyric != true" @click="togglelyric=true" class="lyrics">
                    <ul :style="{'top':lyricTop}">
                        <li :class="{'con':currentRow == index}" v-for="(item,index) in lyric" :key="index">
                            {{item.text}}
                        </li>
                    </ul>
                </div>
                </div>
                <div class="bottom-contorl-box">
                    <!-- 滑块 -->
                    <div class="range">
                        <div class="bar">
                            <span class="timeLeft">{{timeLeft | playerTime}}</span>
                                <van-slider v-model="value" @change="sliderchange" bar-height="4px" active-color="#d43c33">
                                    <template #button>
                                        <div class="custom-button"></div>
                                    </template>
                                </van-slider>
                                <span class="timeRight">{{timeRight | playerTime}}</span>
                        </div>
                    </div>
                    <div class="button">
                        <div class="iconfont icon-xunhuanbofang" @click="changeMode" v-if="playerType == 1"></div>
                        <div class="iconfont icon-random" @click="changeMode" v-else></div>
                        <div class="iconfont icon-shangyishoushangyige" @click="startup"></div>
                        <div class="center" @click.stop="toggleplay">
                            <span class="iconfont icon-ico_zanting_xuanzhong" v-show="!isShow"></span>
                            <span class="iconfont icon-zanting" v-show="isShow"></span>
                        </div>
                        <div class="iconfont icon-xiayigexiayishou" @click="lowerFun"></div>
                        <div :class="['iconfont','icon-aixin',{'active':playerId == aixin}]" @click="like(playerId)"></div>
                    </div>
                </div>
            </div>
        </transition>
        <!-- 播放菜单 -->
        <transition name="playMenu"> 
            <div class="playMenu" v-if="playMenuShow">
                <div class="playMenu-header">
                    <span class="icon iconfont icon-xunhuanbofang" v-if="playerType == 1"></span>
                    <span class="icon iconfont icon-random" v-else></span>
                    <span class="play-type">{{playerType == 1?'顺序播放':'随机播放'}}</span>
                    <span>({{playerLists.length}})</span>
                    <span class="iconfont icon-shanchu topshanchu" @click="del"></span>
                </div>
                <div class="playMenu-lists">
                    <ul>
                        <li v-for="item in playerLists" :key="item.id">
                            <span class="icon iconfont icon-shengyin" v-if="item.id == playerId"></span>
                            <span class="name" @click="editPlayerId(item.id)">{{item.name}}</span>
                            <span class="iconfont icon-cuo shanchu" @click="shanchu(item.id)"></span>
                        </li>
                    </ul>
                </div>
                <div class="bottom-close" @click="playMenuShow = false">关闭</div>
            </div>
        </transition>
    <!-- 系统播放器 -->
    <audio ref="audio" autoplay="true" :src="musicData" @ended="endedFun" @canplay="canplayFun"></audio>
    </div>


</template>

<script>
    import {getSongDetail,getSongUrl,getLyric,getPlaylistTracks} from '../../api/base'
    import {getPlaylistDetail} from "../../api/ranking";
    import {getArtistSongs} from '../../api/singer';
    import { Notify } from 'vant';
    import {getUserPlaylist} from '../../api/my'
    export default {
        data() {
            return {
                isShow:true,
                songName:'您还没有选择音乐',
                musicData:null,
                playerShow:false,//控制大播放器
                playMenuShow:false,//控制播放菜单
                value:0,
                timeLeft:0,
                timeRight:0,
                clearset:null, //定时器
                playerLists:[],  //播放菜单列表
                lyric:[],//歌词
                togglelyric:true,//切换图片跟歌词
                lyricTop:'233px',//歌词开始距离顶部
                currentRow:0, //歌词高亮
                playerType: 1, //播放类型 1列表播放 2 随机播放
                SongDetail:{
                    al:{
                        picUrl:null,
                    },
                },
                aixinflag:false,
                aixin:null,
                pid:null,
            }
          },
        props:['playerId','listId','listSingerId'],
        methods: {
            // 收藏与取消
            like(id){
                this.aixinflag = !this.aixinflag;
                if(this.aixinflag){
                    this.aixin = id
                    getPlaylistTracks({
                        op:'add',
                        pid:this.pid,
                        tracks:id,
                        cookie:window.localStorage.getItem('login')
                    }).then(data=>{
                        console.log(data);
                        if(data.code == 200){
                            Notify({
                                message: '收藏成功',
                                color: 'white',
                                background: '#1989fa',
                                });
                            }else{
                                Notify({
                                message: '收藏失败',
                                color: 'white',
                                background: 'red',
                                });
                             }
                    })
                }else{
                    this.aixin  = null;
                    getPlaylistTracks({
                        op:'del',
                        pid:24381616,
                        tracks:id,
                        cookie:window.localStorage.getItem('login')
                    }).then(data=>{
                        if(data.code == 200){
                            Notify({
                                message: '取消收藏成功',
                                color: 'white',
                                background: '#1989fa',
                                });
                            }else{
                                Notify({
                                message: '取消收藏失败',
                                color: 'white',
                                background: 'red',
                                });
                             }
                    })
                }
            },
            // 滑块功能
            rangeFn(){
                //  清除定时器
                clearInterval(this.clearset);
                // 开启定时器
                this.clearset = setInterval(()=>{
                    let CurrentTime = this.$refs.audio.currentTime; //实时变化时间
                    let duration = this.$refs.audio.duration; //歌总时间
                    this.timeLeft = CurrentTime;
                    // 计算滚动条效果
                    this.value = CurrentTime / duration * 100;
                        // 播放完成
                    if(this.value == 100){
                        // 清除定时器
                        clearInterval(this.clearset);
                        this.$refs.audio.pause();
                        this.isShow = true;
                    }
                },999)
            },
            // 获取歌曲详情
            getSongDetailfun(){
                getSongDetail({ids:this.playerId}).then(data=>{
                    this.SongDetail = data.songs[0];
                    this.songName = data.songs[0].name;
                    // 判断播放列表是否有相同数据
                    let index = this.playerLists.findIndex(item=>item.id == data.songs[0].id);
                    if(index == "-1"){ //数据找不到，数据添加播放列表里面
                        this.playerLists.push(this.SongDetail);
                    }
                })
                // 调用滑块功能
                this.rangeFn();
                this.isShow = false
            },
            // 获取歌曲的路径
            getSongUrlfun(){
                getSongUrl({id:this.playerId}).then(data=>{
                    this.musicData = data.data[0].url;
                })
            },
            // 点击播放与暂停
            toggleplay(){
                if(this.musicData){
                    if(this.isShow){
                        this.$refs.audio.play(); //播放
                        let index = this.playerLists.findIndex(item=>item.id == this.SongDetail.id);
                        if(index == "-1"){ //数据找不到，数据添加播放列表里面
                            this.playerLists.push(this.SongDetail);
                        }
                        // 调用滑块功能
                        this.rangeFn();
                    }else{
                        this.$refs.audio.pause();//暂停
                    }
                    this.isShow = !this.isShow;//切换按钮
                }else{
                    this.isShow = true;
                }
            },
            // 音乐播放结束
            endedFun(){
                this.isShow = true;
                clearInterval(this.clearset);//结束播放
                if(this.playerType == 1){ //列表播放
                    this.lowerFun();//下一首歌
                }else{  //随机播放
                    let index = parseInt(Math.random() * this.playerLists.length);
                    this.$emit("get-player-id",this.playerLists[index].id); //修改父组件值
                }
            },
             // 音乐播放器数据加载完，直接获取歌曲时间
             canplayFun(){
                let duration = this.$refs.audio.duration; //歌总时间
                this.timeRight = duration;
            },
            // 获取滚动条变化
            sliderchange(){
                let duration = this.$refs.audio.duration * this.value / 100;
                this.timeLeft = duration;//修改页面数据
                this.$refs.audio.currentTime = duration;//修改播放器时间
            },
            // 点击菜单栏更改播放id
            editPlayerId(id){
                this.$emit("get-player-id",id)
            },
            // 清空播放列表
            del(){
                this.playerLists = [];
                this.$refs.audio.pause();
                this.isShow = true;
            },
            // 删除播放列表某一首歌
            shanchu(id){
                let index = this.playerLists.findIndex(item => item.id == id)
                if(id == this.playerId){
                    this.$refs.audio.pause();
                    this.isShow = true;
                    this.playerLists.splice(index,1)
                }else{
                    this.playerLists.splice(index,1)
                }
            },
            // 上一首
            startup(){
                let {id} = this.SongDetail;  //获取id
                // 获取再播放列表中下标
                let index = this.playerLists.findIndex(item=>item.id == id);
                // 让自减一，判断是否为第一首歌，上一首歌为歌曲最后一首歌。
                index = index-1 < 0? this.playerLists.length-1:index-1; 
                this.$emit("get-player-id",this.playerLists[index].id); //修改父组件值
            },
            // 下一首
            lowerFun(){
                let {id} = this.SongDetail;  //获取id
                // 获取再播放列表中下标
                let index = this.playerLists.findIndex(item=>item.id == id);
                // 1.让自加一下标，判断是否为最后一首歌，最后一首歌，显示第一首歌播放
                index = index + 1 > this.playerLists.length-1 ? 0:index +1;
                // this.SongDetail = this.playerLists[index];
                this.$emit("get-player-id",this.playerLists[index].id); //修改父组件值
            },
            // 调用接口获取歌词
            getLyricFun(){
                getLyric({id:this.playerId}).then(data=>{
                    this.formatLyric(data.lrc.lyric);
                })
            },
            // 处理歌词结构
            formatLyric(text){
                this.lyric = [];
                let arr = text.split("\n"); //把原歌曲字符串转歌词
                let row = arr.length; //获取数组长度
                for(let i = 0;i < row;i++){
                    let temp_row = arr[i];//获取数据"[00:00.000]
                    let temp_arr = temp_row.split("]");//分成两个数组
                    let lyrictext = temp_arr.pop(); //删除数组最后一个，返回数据
                    temp_arr.forEach(element=>{
                        let obj = {};
                        // "[00:21.45" =>00:21.45
                        let time_arr = element.substr(1,element.length-1).split(":");
                        let s = time_arr[0]*60 + Math.ceil(time_arr[1]);//得到当前秒数
                        obj.text = lyrictext;
                        obj.time = s;
                        if(lyrictext.length > 0){
                            this.lyric.push(obj);//每一行处理好数据放入数组中
                        }
                    })
                }
            },
            // 实时动态显示歌词变化
            lyricInput(){
                let duration = parseInt(this.$refs.audio.duration * this.value / 100);
                for(let i = 0; i < this.lyric.length;i++){
                    if(duration == this.lyric[i].time){
                        this.lyricTop = 210 - i * 36 + "px";
                        this.currentRow = i; //歌词高亮
                        break;
                    }
                }
            },
            // 修改播放类型
            changeMode(){
                this.playerType= this.playerType == 1?2:1
            }

        },
        watch:{
            // 监听歌曲id变化
            playerId(){
                 this.getSongDetailfun(),
                 this.getSongUrlfun(),
                 this.getLyricFun()
            },
            // 监听排行榜id变化
            listId(){
                getPlaylistDetail({id:this.listId}).then(data=>{
                    this.playerLists = data.playlist.tracks;  //获取歌单数据
                })
            },
            // 监听播放时间变化
            timeLeft(){
                for(let i = 0; i < this.lyric.length;i++){
                    if(parseInt(this.timeLeft) == this.lyric[i].time){
                        this.lyricTop = 210 - i * 36 + "px";
                        this.currentRow = i; //歌词高亮
                        break;
                    }
                }
            },
            // 监听歌手id变化
            listSingerId(){
                getArtistSongs({
                    id:this.listSingerId,
                    limit:50,
                }).then(data=>{
                    this.playerLists = data.songs;
                })
            }
        },
        beforeDestroy(){
            clearInterval(this.clearset);
        },
        created() {
            let id = window.localStorage.getItem('uid')
            getUserPlaylist({uid:id}).then(data=>{
                this.pid = data.playlist[0].id;
            })
        },
        // 过滤器
        filters:{
            playerTime(data){
                let m = parseInt(data / 60);// 分钟
                let s = parseInt(data % 60);// 秒
                if(m == 0 && s == 0){
                    return "0:00";
                }else{
                    return m+":"+ (s < 10 ? "0"+ s: s);
                }
            }
        }
    }
</script>

<style lang="less">
    // 小播放器
    .player-box{
        min-width: 320px;
        max-width: 750px;
        height: 54px;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        margin:auto;
        background-color: white;
        display: flex;
        align-items: center;
        box-shadow: 0 0 10px #aaa;
        z-index: 2000;
        .img{
            width: 36px;
            height: 36px;
            border-radius: 50%;
            margin: 0px 10px 0px 18px;
            box-shadow: 0 0 5px #bbb;
            overflow: hidden;
            &.play{
                animation: rotate 20s linear infinite;
            }
            &.pause{
                animation-play-state: paused;
            }
            img{
                display: block;
                width: 37px;
                height: 37px;
                border-radius: 50%;
            }
        }
        .name-box{
            width: 210px;
            margin-right: 10px;
            // height: 25px;
            .song-name{
                width: 100%;
                font-size: 13px;
                color: #262928;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
            .people-name{
                width: 100%;
                font-size: 12px;
                color: #424444;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
        }
        .icon-box{
            width: 30px;
            height: 30px;
            border-radius: 15px;
            position: relative;
            margin-right: 12px;
            .icon{
                display: block;
                position: absolute;
                top:0;
                left: 0;
                font-size: 30px;
                color: #262928;
            }
        }
        .more-box{
            .more{
                font-size: 28px;
                color: #262928;
            }
        }
    }
    // 大播放器
    .big-player{
        min-width: 320px;
        max-width: 750px;
        height: 667px;
        position: fixed;
        // bottom: -667px;
        top: 0;
        left: 0;
        right: 0;
        margin: auto;
        background-color: #7d7977;
        z-index: 3000;
        // 向下箭头
        .icon{
            position: absolute;
            top: 15px;
            left: 15px;
            color: white;
            font-weight: bold;
            z-index: 100;
        }
        // 头部
        .big-player-header{
            width: 100%;
            height: 50px;
            color: white;
            text-align: center;
            border-top: 1px solid transparent;
            box-sizing: border-box;
            .song-name{
                font-size: 16px;
                margin-top:10px;
            }
            .singer-name{
                font-size: 12px;
                color: #fcfcfc;
            }
        }
        // 大图片
        .big-img-box{
            width: 100%;
            height: 467px;
            position: relative;
            overflow: hidden;
            .img{
                width: 275px;
                height: 275px;
                border:14px solid #9a9591;
                border-radius: 50%;
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                margin: auto;
                &.play{
                animation: rotate 20s linear infinite;
                }
                &.pause{
                    animation-play-state: paused;
                }
                img{
                    display: block;
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                }

            }
            ul{
                    position: absolute;
                    width: 100%;
                    text-align: center;
                    top:233px;
                    left:0px;
                    li{
                        height: 36px;
                        line-height: 36px;
                        color:#CBCCCC;
                        font-size: 16px;
                        &.con{
                            color:#fff;
                        }
                    }
                }
        }
        // 底部操作
        .bottom-contorl-box{
            height: 150px;
            width: 100%;
            .button{
                width: 100%;
                height: 65px ;
                display: flex;
                align-items: center;
                justify-content: space-evenly;
                color: white ;
                div:nth-child(1){
                    font-size: 22px;
                }
                div:nth-child(2){
                    font-size: 25px;
                }
                div:nth-child(3){
                    width: 40px;
                    height: 40px;
                    position: relative;
                    span{
                        font-size: 35px;
                        position: absolute;
                        top: 0;
                        left: 0;
                        bottom: 0;
                        right: 0;
                        margin: auto;
                    }
                }
                div:nth-child(4){
                    font-size: 25px;
                }
                div:nth-child(5){
                    font-size: 25px;
                    &.active{
                        color: red;
                    }
                }
            }
        }
    }
        // 滑块
    .range{
            text-align: center;
            height: 20px;
            width: 100%;
            margin-top: 45px;
            .bar{
                width: 246px;
                margin:0 auto;
                color:#fff;
                position: relative;
                font-size: 12px;
                .timeLeft{
                    position: absolute;
                    left:-36px;
                    top:-4px;
                }
                .timeRight{
                    position: absolute;
                    right:-36px;
                    top:-4px;
                }
                .custom-button{
                    width: 5px;
                    height: 5px;
                    border: 5px solid white;
                    border-radius: 50%;
                    background-color: #d43c33;
                }
            }
        }

    .player-enter,.player-leave-to{
        top: 667px;
    }
    .player-enter-to,.player-leave{
        top: 0px;
    }
    
    .player-leave-active,
    .player-enter-active{
        transition: all 0.8s;
    }
    // 旋转动画效果
    @keyframes rotate {
        0%{
            transform: rotate(0);
        }
        100%{
            transform: rotate(360deg);
        }
    }

    // 播放菜单
    .playMenu{
        width: 100%;
        height: 310px;
        border-radius: 10px 10px 0 0 ;
        position: fixed;
        bottom: 0;
        left: 0;
        background-color: white;
        box-shadow: 0 0 5px #aaa;
        z-index: 2000;
        .playMenu-header{
            width:100%;
            height:28px;
            line-height: 28px;
            margin-top: 12px;
            font-size: 16px;
            color: #000;
            .icon{
                margin-left:16px;
            }
            .play-type{
                margin-left:5px;
            }
            .topshanchu{
                float: right;
                margin-right: 16px;
                color: #000;
            }
        }
        .playMenu-lists{
            width: 100%;
            height: 236px;
            overflow-y: scroll;
            ul{
                width: 100%;
                height: 236px;
                li{
                    width: 100%;
                    height:38px;
                    line-height: 38px;
                    text-indent: 10px;
                    .name{
                        display: inline-block;
                        width: 270px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                    .icon{
                        color:#d12012;
                        vertical-align: top;
                        margin-left:10px;
                    }
                    .shanchu{
                        display: inline-block;
                        height: 38px;
                        line-height: 38px;
                        width: 38px;
                        float: right;
                        margin-right: 16px;
                        color:#d12012;
                    }
                }
            }
        }
        .bottom-close{
            width: 100%;
            height:46px;
            line-height:46px;
            text-align: center;
            font-size: 16px;
            position: absolute;
            bottom: 0;
            left: 0;
            color:#0c0b0a;
            letter-spacing: 0.5px;
            background-color: white;
        }
    }

    .playMenu-enter,.playMenu-leave-to{
        bottom:-310px;
    }
    .playMenu-enter-to,.playMenu-leave{
        bottom: 0px;
    }
    
    .playMenu-leave-active,
    .playMenu-enter-active{
        transition: all 0.8s;
    }

</style>